package com.mall.users.service;
import java.util.Date;

import com.mall.commons.exception.BusinessException;
import com.mall.model.domain.UmsMenu;
import com.mall.model.domain.UmsResource;
import com.mall.model.vo.CommonPage;
import com.mall.users.mapper.UmsResourceMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class UmsResourceService {

    @Autowired
    private UmsResourceMapper umsResourceMapper;
    public List<UmsResource> selectByIds(List<Long> ids) {
        return umsResourceMapper.selectByIds(ids);
    }

    /**
     * 查询所有后台资源
     * @return
     */
    public List<UmsResource> listAll() {
        return umsResourceMapper.selectAll();
    }

    /**
     * 分页模糊查询后台资源
     * @param map
     * @return
     */
    public CommonPage list(Map map) {
        String categoryIdStr = (String) map.get("categoryId");
        Long categoryId = null;
        if (StringUtils.isNotEmpty(categoryIdStr)) {
            categoryId = Long.valueOf(categoryIdStr);
        }
        String nameKeyword = (String) map.get("nameKeyword");
        String urlKeyword = (String) map.get("urlKeyword");
        Integer pageNum = Integer.valueOf(map.get("pageNum").toString()) ;
        Integer pageSize = Integer.valueOf(map.get("pageSize").toString()) ;
        UmsResource resource = new UmsResource();
        resource.setName(nameKeyword);
        resource.setUrl(urlKeyword);
        resource.setCategoryId(categoryId);
        Integer count = umsResourceMapper.selectCount(resource);
        List<UmsResource> list = umsResourceMapper.selectByPage(resource,pageSize,pageNum);
        return new CommonPage(pageNum,pageSize,count,list);
    }

    /**
     * 根据ID获取资源详情
     * @param id
     * @return
     */
    public UmsResource getById(Long id) {
        return umsResourceMapper.selectById(id);
    }

    /**
     * 根据ID删除资源
     * @param id
     * @return
     */
    public void delete(Long id) {
        umsResourceMapper.delete(id);
    }

    /**
     * 添加后台资源
     * @return
     */
    public void create(UmsResource umsResource) {
        UmsResource resource = umsResourceMapper.selectByName(umsResource.getName());
        if (resource!= null) {
            throw new BusinessException("资源名称已存在");
        }
        umsResource.setCreateTime(new Date());
        umsResourceMapper.save(umsResource);
    }

    /**
     * 修改后台资源
     * @param umsResource
     * @return
     */
    public void update(UmsResource umsResource) {
        UmsResource resource = umsResourceMapper.selectByName(umsResource.getName());
        if (resource!= null) {
            throw new BusinessException("资源名称已存在");
        }
        umsResourceMapper.update(umsResource);
    }
}
